from fastapi import Depends, HTTPException, status, Request
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError
from sqlalchemy.ext.asyncio import AsyncSession

from logger import logger
from project.user.service import get_user_by_id
from project.user.util import extract_token

oauth2_scheme = OAuth2PasswordBearer(tokenUrl='auth/login')


# 创建一个依赖函数，用于获取会话
def get_db(request: Request):
    return request.state.db


async def get_current_user(token: str = Depends(oauth2_scheme), db: AsyncSession = Depends(get_db)):
    """
    获取当前登录用户
    :param token:
    :param db:
    :return:
    """
    invalid_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="无效的用户数据",
        headers={'WWW-Authenticate': 'Bearer'}
    )
    try:
        id: int = extract_token(token)
        if id is None:
            raise invalid_exception
    except JWTError:
        raise invalid_exception
    db_user = await get_user_by_id(db, id)
    if db_user is None or db_user.state is False:
        raise invalid_exception
    return db_user


# 以下为redis数据库配置
async def get_redis():
    pool = await redis_client.get_pool()
    try:
        await pool.ping()
    except:
        try:
            redis_client._pool = await redis_client._create_pool()
            pool = redis_client._pool
            await pool.ping()
        except Exception as e:
            logger.error(f"Redis 错误: {str(e)}")
            # 捕获 Redis 相关的其他异常
            raise HTTPException(status_code=503, detail=f"Redis 错误: {str(e)}")

    return pool
